﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mortgage.DAL.Entity;

namespace Mortgage.Form
{
    public partial class CodeTable : System.Web.UI.Page
    {
        Mortgage.Srv.IConfigTypeSrv svcConfigType = Mortgage.Srv.SrvFactory.CreateConfigTypeSrv();
        Mortgage.Srv.IConfigSrv svc = Mortgage.Srv.SrvFactory.CreateConfigSrv();

        Mortgage.Srv.IInterestRateSrv svcInter = Mortgage.Srv.SrvFactory.CreateInterestRateSrv();

        #region property
        public tzConfig Entity
        {
            get;
            set;
        }

        public EnmFormMode FormMode
        {
            get
            {
                if (ViewState["_ViewState"] == null)
                    return EnmFormMode.Blank;
                EnmFormMode result = (EnmFormMode)Enum.Parse(typeof(EnmFormMode), ViewState["_ViewState"].ToString());
                return result;

            }
            set
            {
                ViewState["_ViewState"] = value;
            }
        }

        public bool IsSystemCodeTabe
        {
            get
            {
                return ViewState["__IsSystem"] == null ? false : Convert.ToBoolean(ViewState["__IsSystem"]);
            }
            set
            {
                ViewState["__IsSystem"] = value;
            }
        }
        #endregion

        #region event handler

        protected void Page_Load(object sender, EventArgs e)
        {
            grid.RowDataBound += new GridViewRowEventHandler(grid_RowDataBound);
            if (!Page.IsPostBack)
            {
                BindConfigType();

                grid.PageIndex = 1;
                BindGridView();

                FormMode = EnmFormMode.Blank;
                HandleFormState(FormMode);

            }
        }

        protected void drpConfigType_SelectedIndexChanged(object sender, EventArgs e)
        {
            grid.PageIndex = 1;
            BindGridView();
            string cfTypeCode = drpConfigType.SelectedValue;
            tzConfigType cfType = svcConfigType.GetByCode(cfTypeCode);
            if (cfType != null)
                IsSystemCodeTabe = cfType.IsSystem;

            FormMode = EnmFormMode.Blank;
            HandleFormState(FormMode);

            
        }

        void grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                e.Row.Attributes["onmouseover"] = "this.style.cursor='pointer';";
                e.Row.Attributes["onmouseout"] = "this.style.cursor='default';";

                e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grid, "Select$" + e.Row.RowIndex);
            }
        }

        protected void grid_SelectedIndexChanged(object sender, EventArgs e)
        {
            int id = Convert.ToInt32(grid.DataKeys[grid.SelectedIndex].Value.ToString());
            tzConfig usr = svc.GetById(id);
            if (usr == null)
                Entity = new tzConfig();
            else
                Entity = usr;

            // Update mode
            FormMode = EnmFormMode.Edit;
            HandleFormState(FormMode);
            BindView();

        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            // Update mode
            Entity = new tzConfig() { };
            FormMode = EnmFormMode.Insert;
            HandleFormState(FormMode);
            BindView();

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;
            BindEntity();
            // clear error Message
            DialogMess.Text = string.Empty;
            DialogMess.CssClass = "successBox";
            if (FormMode == EnmFormMode.Insert) // Insert Mode
            {

                try
                {
                    if (svc.Insert(Entity) == 0)
                    {
                        DialogMess.Text = "Cập nhật thành công!";
                        BindGridView();

                        // Translate to update mode
                        // Update mode
                        FormMode = EnmFormMode.Edit;
                        HandleFormState(FormMode);
                        BindView();
                    }
                }
                catch (Exception ex)
                {
                    DialogMess.Text = ex.Message;
                    DialogMess.CssClass = "failureBox";
                }


            }
            else
            {

                if (svc.Update(Entity) == 0)
                {

                    DialogMess.Text = "Cập nhật thành công!";
                    BindGridView();

                    // Translate to update mode
                    // Update mode
                    FormMode = EnmFormMode.Edit;
                    HandleFormState(FormMode);
                    BindView();
                    
                }


            }
            Utility.RestMortgageStatus();
            

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            BindEntity();
            svc.Delete(Entity);
            BindGridView();
            FormMode = EnmFormMode.Blank;
            HandleFormState(FormMode);
        }


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            FormMode = EnmFormMode.Blank;
            HandleFormState(FormMode);
        }

        #endregion

        #region function

        void BindConfigType()
        {
            drpConfigType.DataSource = svcConfigType.GetAll();
            drpConfigType.DataBind();
        }

        void BindGridView()
        {
            string code = drpConfigType.SelectedValue.ToString();

            grid.DataSource = svc.GetAll(code);
            grid.DataBind();

        }

        protected void HandleFormState(EnmFormMode state)
        {
            switch (state)
            {
                case EnmFormMode.Blank:
                    btnCancel.Enabled = false;
                    btnDelete.Enabled = false;
                    if (drpConfigType.SelectedIndex > 0 && !IsSystemCodeTabe)
                        btnNew.Enabled = true;
                    else
                        btnNew.Enabled = false; // Dont new for code _blank
                    btnSave.Enabled = false;


                    BlankControl();
                    EnableControl(false);
                    Entity = new tzConfig();

                    break;
                case EnmFormMode.Edit:
                    btnCancel.Enabled = true;
                    if (IsSystemCodeTabe) // No delete System code table
                    {
                        btnDelete.Enabled = false;
                        btnNew.Enabled = false;
                    }
                    else
                    {
                        btnDelete.Enabled = !(svcInter.Find(Entity.ID, null, null).Count > 0 );
                        btnNew.Enabled = true;
                    }

                    btnSave.Enabled = true;

                    EnableControl(true);

                    break;
                case EnmFormMode.Insert:
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = false;
                    btnNew.Enabled = false;
                    btnSave.Enabled = true;

                    EnableControl(true);

                    break;
            }

            BindView();
        }

        protected void EnableControl(bool enable)
        {

            fldValue.Enabled = enable;

            fldSortOrder.Enabled = enable;
            fldDescription.Enabled = enable;

        }

        protected void BindView()
        {
            fldValue.Text = Entity.Value;
            fldSortOrder.Text = Entity.SortOrder.ToString();
            fldDescription.Text = Entity.Description;
            fldID.Value = Entity.ID.ToString();

            fldIsSystem.Text = IsSystemCodeTabe.ToString();
        }

        protected void BindEntity()
        {
            tzConfig entity = new tzConfig();
            if (Entity != null)
                entity.ID = Entity.ID;

            entity.Code = drpConfigType.SelectedValue.ToString();

            entity.ID = Convert.ToInt32(fldID.Value);
            entity.Value = fldValue.Text;
            entity.SortOrder = Convert.ToInt32(fldSortOrder.Text.Trim());

            entity.Description = fldDescription.Text.Trim();
            Entity = entity;
        }

        protected void BlankControl()
        {
            fldValue.Text = string.Empty;
            fldSortOrder.Text = string.Empty;
            fldDescription.Text = string.Empty;
            fldID.Value = string.Empty;

            DialogMess.CssClass = string.Empty;
            DialogMess.Text = string.Empty;

        }

        #endregion


    }
}